# -*- coding:utf-8 -*- ＃
'''
Created on 2012-8-2

'''
from flask import Flask, jsonify, json, Response
from flask.globals import request
from data_access.user_data_access import UserDataAccess
import logging
from logging.handlers import RotatingFileHandler
from auth import requires_auth
from datetime import datetime
import os
from common.status_code import Status

app = Flask(__name__);

# Initialize the logger
"""User: www-data needs write permission in order to write to the log file in /var/www folder. 
   If permission denied, try to run following commands in terminal:
     sudo chgrp -R www-data /var/www
     sudo chmod -R g+w /var/www
   Refer to: http://superuser.com/questions/19318/how-can-i-give-write-access-of-a-folder-to-all-users-in-linux
"""
logFileName = "/var/www/taxi-svc.log";
try:
    file_handler = RotatingFileHandler(filename=logFileName, maxBytes=1024 * 1024, encoding="utf-8");
except:
    logFileName = os.path.dirname(__file__) + "/taxi-svc.log";
    file_handler = RotatingFileHandler(filename=logFileName, maxBytes=1024 * 1024, encoding="utf-8");
    
app.logger.addHandler(file_handler)
app.logger.setLevel(logging.DEBUG)

@app.route("/", methods=["GET"])
@requires_auth
def index():
    """Returns the server status
    """
    data = {"status": Status.OK, "message": "Server is OK."};
    resp = jsonify(data);
    resp.status_code = 200;
    
    return resp;

@app.route("/test/var1=<var1>&var2=<var2>&var3=<var3>", methods=["GET"])
def test(var1, var2, var3):
    data = {"var1": str(var1), "var2": str(var2), "var3": str(var3)};
    resp = jsonify(data);
    resp.status_code = 200;
    
    return resp;
    
@app.route("/user/<int:user_id>", methods=["GET"])
@requires_auth
def get_user_by_id(user_id):
    """Get user information by user id
    """
    app.logger.debug("Invoke API: get_user_by_id(user_id={0})".format(user_id));
    
    userDataAccess = UserDataAccess();
    data = userDataAccess.get_user_by_id(user_id);
    
    resp = Response(data, status=200, mimetype='application/json');
    resp.status_code = 200;
    
    return resp;

@app.route("/add_user", methods=["POST"])
@requires_auth
def add_user():
    """Create a new user
    """
    if request.headers['Content-Type'] == 'application/json':
        user = request.json;
        
        userDataAccess = UserDataAccess();
        userDataAccess.add_user(user);  
        
        resp = Response({"status":Status.OK}, status=200, mimetype='application/json');
        resp.status_code = 200;
        
        return resp;
    else:
        json = {"status": "error",
                "message": "415 Unsupported Media Type; You should use 'application/json' as Content-Type." };
        resp = jsonify(json);
        resp.status_code = 415;
        
        return resp;
     
@app.errorhandler(Exception)
def error(error=None):
    """Global exception handler
    """
    message = "Bad request: {0}".format(request.url);
    if error:
        message = str(error);
 
    result = {"status":Status.ERROR, "message": message};
    resp = jsonify(result);
    resp.status_code = 500;
    
    app.logger.error("[Error][{0}]".format(str(datetime.now()), message));
    
    return resp;

@app.errorhandler(404)
def error404(error=None):
    message = "Bad request: {0}".format(request.url);
 
    result = {"status":Status.ERROR, "message": message};
    resp = jsonify(result);
    resp.status_code = 200;
    
    return resp;
